//
//  CYLaunchAdvertisementManager.m
//  cyjf
//
//  Created by tauCross on 2017/8/28.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYLaunchAdvertisementManager.h"



#define LaunchAdvertisement_Path @"lanch_advertisement"



@implementation CYLaunchAdvertisementObject

MJExtensionCodingImplementation

@end



@implementation CYLaunchAdvertisementManager

+ (instancetype)standardManager
{
    static CYLaunchAdvertisementManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CYLaunchAdvertisementManager alloc] init];
    });
    return manager;
}

- (void)fetchLocalObjectWithResult:(void(^)(CYLaunchAdvertisementObject *object))result
{
    [CYStandardDataAPI advertisement_getListWithPosition:CYDataAPIAdvertisementPositionLaunch page_no:nil complete:^(CYResponse *response) {
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
            CYDataAPIAdvertisementModel *model = nil;
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:LaunchAdvertisement_Path];
            if(response.code == 0)
            {
                if([response.content isKindOfClass:[NSArray class]] && [response.content count])
                {
                    model = [CYDataAPIAdvertisementModel mj_objectWithKeyValues:[response.content firstObject]];
                }
                else
                {
                    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if(result)
                        {
                            result(nil);
                        }
                    });
                    return;
                }
            }
            CYLaunchAdvertisementObject *object = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if(object == nil || (model && ![object.model.id isEqual:model.id]))
            {
                object = [[CYLaunchAdvertisementObject alloc] init];
                object.model = model;
                object.image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:model.image.tc_url]];
                if(object.image)
                {
                    [NSKeyedArchiver archiveRootObject:object toFile:path];
                }
                else
                {
                    object = nil;
                    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result)
                {
                    result(object);
                }
            });
        });
    }];
}

@end
